require 'rubygems'
require 'gruff'
require "report/Report"
require "report/Section"

class AverageDurationPerCorrectCharacter
    NAME = "Average Duration Between 2 Correct Characters"
    
  
    def analyze(directory, experimentalData, phraseCards)
      
      #create the report
      report = Report.new(directory, NAME)
      
      #get the data
      data = experimentalData.group_by_set
          
      data.each_pair do |set, entries|
        data_by_uid = {}
        
        entries.each do |e|
          #initialize if nil
          data_by_uid[e.uid] ||= []
          data_by_uid[e.uid] << e
        end
        
        #create a graph for each set
        g = create_graph(set)
        
        #do some simple statistics
        stat = ""
        
        #average value of each subject
        avg_durations_by_subject = []
        
        #Generate a section for each tech phrase
        data_by_uid.each_pair do |uid, entries|
           entries.sort! { |x,y| x.date <=> y.date }
          

           avg_durations = entries.collect do |e|
             _get_avg_duration(e)
           end  
                  
           avg = avg_durations.inject{ |sum, el| sum + el }.to_f / avg_durations.length
           avg_durations_by_subject << avg    
           g.data "Subject:#{uid}", avg_durations
           stat = stat + "<b>Subject #{uid}:</b> " +  
                  "finished(phrases):#{entries.length} " +
                  "average duration: #{avg}" +
                  "<br/>" 
        end
        
        avg = avg_durations_by_subject.inject{ |sum, el| sum + el }.to_f / avg_durations_by_subject.length
        stat = stat + "<b>Average: </b> #{avg} <br/>"
        
        report.new_section("Set #{set}", stat, g)  
          
      end
  
      #generate report  
      report.to_html
    end
    
   
    #  S  t  u  s  bs   d  e  n  t
    #   t1 t2 D  D   t5  t6 t7 t8
    def _get_avg_duration(e)
      #marks the time duratin the have to be deleted
      marks = []
      e.sequence.each do |seq|
        marks << 0
        if ( seq[0].eql?("\b"))
          marks[-2] = 1
          marks[-3] = 1 unless marks[-3] == nil
        end
      end
      
      durations = []
      marks[-1] = 1 # remove the last one which is always zero  
      marks.length.times do |i|
        durations << e.sequence[i][1] unless marks[i]==1
      end
            
      return durations.inject{ |sum, el| sum + el }.to_f / durations.length
    end
    
    def create_graph (set)
      g = Gruff::Line.new
      g.dot_radius = 2
      g.line_width = 2
      g.x_axis_label = "Phrases"
      g.y_axis_label = "Time (10 ms)"
      g.title = "Avg Duration Between Characters(Set:#{set})"
      g
    end
end